package com.action.boot.jpa.controller;

import com.action.boot.jpa.config.web.ApiResult;
import com.action.boot.jpa.repository.UserInfo;
import com.action.boot.jpa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by Wuxiang on 2017/3/25.
 */
@RestController
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping(value = "/findAll", method = RequestMethod.GET)
    public ApiResult findAll() {
        Iterable<UserInfo> userInfos = userService.findAll();
        return ApiResult.success("成功查询到所有的userInfo！", userInfos);
    }

    @RequestMapping(value = "/name", method = RequestMethod.GET)
    public ApiResult findByName(@RequestParam String name) {
        List<UserInfo> infos = userService.findByName(name);
        return ApiResult.success("成功根据name查询到userinfo！", infos);
    }

    @RequestMapping(value = "/age", method = RequestMethod.GET)
    public ApiResult findAgeNull() {
        List<UserInfo> userInfos = userService.findAgeNull();
        return ApiResult.success("成功查询到age为空的数据", userInfos);
    }

    @RequestMapping(value = "/age/{age}", method = RequestMethod.GET)
    public ApiResult findByAge(@PathVariable String age) throws Exception {
        List<UserInfo> userInfos = userService.findByAge(age);
        return ApiResult.success("成功查询根据age查询到user", userInfos);
    }

    @RequestMapping(value = "/id/{id}", method = RequestMethod.GET)
    public ApiResult findById(@PathVariable Long id) {
        UserInfo userInfo = userService.findById(id);
        return ApiResult.success("根据id查询到用户信息！", userInfo);
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public ApiResult deleteById(@PathVariable Long id) {
        userService.deleteById(id);
        return ApiResult.success("已删除id为 " + id + "的用户");
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ApiResult update(@ModelAttribute UserInfo userInfo) {
        userService.update(userInfo);
        return ApiResult.success("已更新id为 " + userInfo.getId() + "的用户");
    }

    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public ApiResult insert(@ModelAttribute UserInfo userInfo) {
        UserInfo user = userService.insert(userInfo);
        return ApiResult.success("已增加id为 " + userInfo.getId() + "的用户", user);
    }
}
